$(function() {
    // $('p').on('click', function() {
    //     $(this).css('background', 'yellow')
    // })
    /******************静态事件区************* */
    let count = 7;
    let offset = 0;
    $('.panel-heading').hover(function() {
        $(this).toggleClass('bor')
    })
    $('.pagination li').click(function() {
        $('.pagination li').removeClass('active').removeAttr('aria-current')
        $(this).addClass('active').attr('aria-current', 'page')
    })
    $('#esc-user').click(function() {
        // alert(0)
        var msg = '您是否确定要退出当前操作！'
        if (confirm(msg) == true) {
            location.href = '/login'
            return true
        }
    });


    /*****************初始化获取用户信息************** */
    getUserInfo();

    function getUserInfo() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }

        $.ajax({
            type: 'POST',
            url: 'http://localhost:5001/userInfo',
            data: {
                token
            },
            success(result) {
                console.log(result)
                if (result.code == 303) {
                    if (confirm('您的身份信息已过期，请重新登录')) {
                        location.href = '/login'
                    }

                }
                if (result.code == 400) {
                    $('#user-img').attr('src', result.result[0].url)
                    $('#username').html(result.result[0].user)
                }

            }

        })
    }
    /*********************************** */


    /**************添加商品类型或者编辑商品类型********************** */
    $('#preserve-shoptype').on('click', function() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        let typename = $('#typename').val();
        if (typename.trim() == '') {
            alert('类型不能为空空！');
            return;
        }
        if ($('#exampleModalLabel').text() == '编辑商品类型') {
            $.ajax({
                type: 'POST',
                url: 'http://localhost:5001/editType',
                data: {
                    typeId,
                    typename,
                    token,
                },
                success(result) {
                    console.log(result)
                    if (result.code == 111) {
                        location.reload()
                    }
                }
            })

        } else {
            $.ajax({
                type: 'POST',
                url: 'http://localhost:5001/addType',
                data: {
                    token,
                    typename
                },
                success(result) {
                    console.log(result)
                    if (result.msg == '添加商品类型成功') {
                        $('#exampleModal').modal('hide');
                        $('#typename').val('')
                    }
                }
            })
        }

    });
    /******************************************** */


    /******************初始化获取商品数据类型*************************** */
    getTypeData();

    function getTypeData() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        //获取搜索类型名称
        let data = {
            token,
            count,
            offset,
        }
        let typename = $('#typename1').val();

        if (typename.trim() !== '') {
            // alert(typename)
            data.typename = typename

        }
        // console.log(data)

        $.ajax({
            type: 'GET',
            url: 'http://localhost:5001/findType',
            data,
            success(result) {
                console.log(result)
                if (result.msg == '查询数据类型成功') {
                    $('tbody').empty()

                    result.result.forEach((obj, i) => {
                        obj.created_at = timeUtils.formatDate(obj.created_at)
                        obj.updated_at = timeUtils.formatDate(obj.updated_at)
                        let tr = `<tr id="${obj.shop_type_id}">
                        <th scope="row" class="nums">${i+1}</th>
                        <td  class='t-name'>${obj.shop_type_name}</td>
                        <td class="status">${obj.status==1?'启用':'禁用'}</td>
                        <td>${obj.created_at}</td>
                        <td>${obj.updated_at}</td>
                        <td>
                            <button type="button" class="btn btn-primary btn-sm edited" >编辑</button>
                            <button type="button" class="btn btn-warning btn-sm ${obj.status==1?'':'hides'}" id="disable-btn">禁用</button>
                            <button type="button" class="btn btn-secondary btn-sm ${obj.status==0?'':'hides'}" id="enable-btn">启用</button>
                            <button type="button" class="btn btn-danger  btn-sm remove-btn">删除</button>
                        </td>
                        </tr>`;
                        $('tbody').append(tr)
                    })

                }

            }

        })
    }
    $('#basic-addon2').on('click', function() {
        getTypeData()
    });
    /********************************************* */




    /**************创建一个处理时间的类******************************* */
    class TimeUtils {
        formatDate(value) {
            let date = new Date(value);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            month = month >= 10 ? month : '0' + month;
            let day = date.getDate();
            day = day >= 10 ? day : '0' + day;
            let hours = date.getHours();
            hours = hours >= 10 ? hours : '0' + hours;
            let minutes = date.getMinutes();
            minutes = minutes >= 10 ? minutes : '0' + minutes;
            let seconds = date.getSeconds();
            seconds = seconds >= 10 ? seconds : '0' + seconds;
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    }
    let timeUtils = new TimeUtils;
    /****************************************** */




    /********************编辑商品类型的id(区分编辑和添加分类)************************** */
    let typeId = ''
    $('tbody').on('click', '.edited', function(togg) {
        // console.log('被点击了')
        $('#exampleModalLabel').text('编辑商品类型')
        $('#exampleModal').modal('show')
        let typename = $(this).parents('tr').find('.t-name').text()
        $('#typename').val(typename)
        typeId = $(this).parents('tr').attr('id')
    })
    $('.btn-warning1').on('click', function() {
        $('#typename').val('')
        $('#exampleModalLabel').text('添加商品类型')
    });
    /******************************************** */

    /**************************禁用启用删除控制区*************** */
    $('tbody').on('click', '#disable-btn', function() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        let tr = $(this).parents('tr')
        $(this).hide()
        $(this).next('#enable-btn').show();
        let typeId = tr.attr('id');
        console.log(typeId)
        tr.find('.status').text('禁用');

        // console.log(tr)
        $.ajax({
            type: 'POST',
            url: 'http://localhost:5001/disableType',
            data: {
                token,
                typeId,

            },
            success(result) {
                console.log(result)
            }

        })
    })
    $('tbody').on('click', '#enable-btn', function() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        let tr = $(this).parents('tr')
        $(this).hide()
        let typeId = tr.attr('id');
        $(this).prev('#disable-btn').show();
        tr.find('.status').text('启用');
        // console.log(tr)
        $.ajax({
            type: 'POST',
            url: 'http://localhost:5001/enableType',
            data: {
                token,
                typeId,

            },
            success(result) {
                console.log(result)
            }

        })

    });
    //注意区分假删除（逻辑删除）和真删除（物理删除），商品类型模型中已开启真删除//

    $('tbody').on('click', '.remove-btn', function() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        let tr = $(this).parents('tr');
        let typeId = tr.attr('id')
        $.ajax({
            type: 'POST',
            url: 'http://localhost:5001/removeType',
            data: {
                token,
                typeId,
            },
            success(result) {
                console.log(result)
                if (result.code == 999) {
                    tr.remove()
                    $('tbody').find('.nums').each(function(i) {
                        console.log($('.nums')[0])
                        $(this).text(i + 1)
                    })
                }
            }
        })
    });
    /***************************************** */


    /******************************查询商品分类总页数********************** */
    let currentpage = 1;
    let totalpage = 0;
    let lastactiveid = 0
    getTypeCount()

    function getTypeCount() {
        let token = sessionStorage.getItem('_tk')
        if (!token) {
            //token不存在返回登录页面
            location.href = '/login';
            return
        }
        $.ajax({
            type: 'GET',
            url: 'http://localhost:5001/count',
            data: {
                token,
            },
            success(result) {
                console.log(result);
                if (result.code = 999) {
                    totalpage = Math.ceil(result.result / count);
                    lastactiveid = 'item' + totalpage
                    console.log(lastactiveid)
                    $('#totalpage').text(totalpage)
                    for (let i = 1; i < totalpage; i++) {
                        let li = `<li class="page-item " id="item${i+1}"><a class="page-link" href="javascript:;">${i+1}</a></li>`
                        $('#nextpage').before(li)
                    }
                }
            }
        })
    }
    /****************************************************************** */

    /******************************分页处理区 */
    $('.pagination').on('click', '.page-item', function() {
        //控制上下页的禁用启用
        if ($(".pagination .active ").prev().attr('id') !== 'prevpage') {
            $('#prevpage').removeClass('disabled')
        } else {
            $('#prevpage').addClass('disabled')
        }
        if ($(".pagination .active ").attr('id') == lastactiveid) {
            $("#nextpage").addClass('disabled')
        } else {
            $("#nextpage").removeClass('disabled')
        }
        $('.page-item').removeClass('active').removeAttr('aria-current')
        $(this).addClass('active').attr('aria-current', "current")
        console.log($('.pagination .active a').text())
            // count = 3 * ();
        offset = count * ($('.pagination .active a').text() - 1)
        getTypeData()
    });
    $('#nextpage').on('click', function() {
        if ($('.active').attr('id') == lastactiveid) {
            return
        }
        $('.active').removeClass('active').removeAttr('aria-current')
            .next('.page-item').addClass('active').attr('aria-current', "current")
        offset += count
        currentpage += 1
        getTypeData()
            // console.log(offset, currentpage)

    })
    $('#prevpage').on('click', function() {
            if ($('.active').attr('id') == 'item1') {
                return
            }
            $('.active').removeClass('active').removeAttr('aria-current')
                .prev('.page-item').addClass('active').attr('aria-current', "current")
            offset -= count
            currentpage -= 1
            getTypeData()
                // console.log(offset, currentpage)
        })
        /*******************************/
})